package com.siyoumi.app.modules.sh.service;

import com.siyoumi.app.entity.ShCmd;
import com.siyoumi.app.service.ShCmdService;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class SvcShCmd {
    static public SvcShCmd getBean() {
        return XSpringContext.getBean(SvcShCmd.class);
    }

    static public ShCmdService getApp() {
        return ShCmdService.getBean();
    }

    public JoinWrapperPlus<ShCmd> listQuery() {
        return listQuery(InputData.getIns());
    }

    /**
     * select
     *
     * @return query
     */
    public JoinWrapperPlus<ShCmd> listQuery(InputData inputData) {
        String desc = inputData.input("desc");

        JoinWrapperPlus<ShCmd> query = getApp().join();
        query.eq("scmd_x_id", XHttpContext.getX());
        //排序
        query.orderByAsc("scmd_run")
                .orderByAsc("scmd_run_date");
        if (XStr.hasAnyText(desc)) { //描述
            query.like("scmd_desc", desc);
        }

        return query;
    }

    @Transactional(rollbackFor = Exception.class)
    public XReturn delete(List<String> ids) {
        getApp().delete(ids);

        return EnumSys.OK.getR();
    }


    public XReturn setRun(String id, Integer run) {
        return setRun(id, run, "");
    }

    /**
     * 标记已运行
     *
     * @param id
     * @param run 0:待执行；1：已完成；10：执行中；
     */
    public XReturn setRun(String id, Integer run, String runReturnMsg) {
        ShCmd entity = getApp().getEntity(id);
        if (entity == null) {
            return EnumSys.ERR_VAL.getR("id异常");
        }
        if (entity.getScmd_run().equals(run)) {
            return XReturn.getR(20053, "已操作");
        }

        ShCmd entityUpdate = new ShCmd();
        entityUpdate.setScmd_run(run);
        entityUpdate.setScmd_run_return(runReturnMsg);
        getApp().saveOrUpdatePassEqualField(entity, entityUpdate);

        return EnumSys.OK.getR();
    }
}
